﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities;

namespace XDQ.VAT
{
    public static class EntityExtends
    {
        public static TEntity SetPropertyValue<TEntity, TProperty>(this TEntity entity, [NotNull] Expression<Func<TEntity, TProperty>> propertyExpression, TProperty value)
            where TEntity : Entity
        {
            var prop = ToProperty(propertyExpression);
            if(!prop.CanWrite)
            {
                throw new NotSupportedException($"{typeof(TEntity)}.{prop.Name} is readonly!");
            }
            prop.SetValue(entity, value);
            return entity;
        }

        public static PropertyInfo ToProperty<TObject, TProperty>([NotNull] Expression<Func<TObject, TProperty>> propertyExpression)
        {
            MemberExpression member = null;
            if (propertyExpression.Body is UnaryExpression)
            {
                UnaryExpression expression = (UnaryExpression)propertyExpression.Body;
                if (expression.Operand is MemberExpression)
                {
                    member = (MemberExpression)expression.Operand;
                }
                else
                {
                    throw new ArgumentException($"{expression.Operand} should be a member expression!");
                }
            }
            else if (propertyExpression.Body is MemberExpression)
            {
                member = (MemberExpression)propertyExpression.Body;
            }
            if (member == null)
            {
                throw new ArgumentException($"{propertyExpression} should be a member expression!");
            }
            if (member.Member is PropertyInfo)
            {
                var prop = (PropertyInfo)member.Member;
                return prop;
            }
            else
            {
                throw new ArgumentException($"{propertyExpression} should be a property expression!");
            }
        }

        public static List<PropertyInfo> ToProperties<TObject, TProperty>(params Expression<Func<TObject, TProperty>>[] propertyExpressions)
        {
            return propertyExpressions.Select(x => ToProperty<TObject, TProperty>(x)).ToList();
        }
    }
}
